package com.self.cloudmall.sso.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.self.cloudmall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

@Slf4j
public class SmsUtil {

    private static final String SUCCESS = "OK";
    private static final String RANDOMCODE = "1234567890";

    /**
     * 发送验证码
     * @param accessKeyId
     * @param accessSecret
     * @param signName
     * @param TemplateCode
     * @param phone
     * @return
     */
    public static R sendCode(String accessKeyId,String accessSecret,String signName,
                             String templateCode,String phone,String templateParam){
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam",templateParam);
        try {
            CommonResponse response = client.getCommonResponse(request);
            if (StringUtils.isNotEmpty(response.getData())){
                JSONObject jsonObject = JSONObject.parseObject(response.getData());
                log.info("发送短信验证码返回结果：{}",jsonObject.toJSONString());
                if (jsonObject.containsKey("Code") && SUCCESS.equalsIgnoreCase(jsonObject.getString("Code"))){
                    return R.ok();
                }
                return R.error(jsonObject.containsKey("Message")?jsonObject.getString("Message"):"验证码异常");
            }
            return R.error("短信服务异常");
        } catch (Exception e) {
           log.error("发送短信验证码错误：{}",e);
           return R.error("发送短信验证码错误");
        }
    }

    public static String valideCode(int len){
        String str = "";
        for(int i = 0; i < len; i++) {
            str += RANDOMCODE.charAt((int) Math.floor(Math.random() * RANDOMCODE.length()));
        }
       return str;
    }
}
